package com.silence.gmall.base;

import com.google.common.collect.Lists;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import lombok.experimental.SuperBuilder;
import org.apache.commons.collections4.CollectionUtils;

import java.io.Serial;
import java.io.Serializable;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

/**
 * @Author silence
 * @Date 2025-08-26 13:26
 * @Email 792245022@qq.com
 * @Version 1.0
 * @Description
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
@Accessors(chain = true)
@SuperBuilder(toBuilder = true, builderMethodName = "treeNodeBuilder")
public class TreeNode<T> implements Serializable {

    /**
     * 序列号
     */
    @Serial
    private static final long serialVersionUID = 1L;

    /**
     * 主键
     */
    private String id;

    /**
     * 父主键
     */
    private String parentId;

    /**
     * 排序
     */
    private Long sort;

    /**
     * 子节点集合
     */
    private List<T> childrenList;

    /**
     * 构建树形结构
     *
     * @param groupMap 分组Map
     * @param parentId 父ID
     * @return 树形结构
     */
    public static <U extends TreeNode<U>> List<U> buildTreeListByGroupMap(Map<String, List<U>> groupMap,
                                                                          String parentId) {
        // 获取当前节点集合
        List<U> groupList = groupMap.get(parentId);
        if (CollectionUtils.isEmpty(groupList)) {
            return Lists.newArrayList();
        }

        // 先排序，再设置子节点
        List<U> sortedList = groupList.stream()
                .sorted(Comparator.comparing(TreeNode::getSort,
                        Comparator.nullsLast(Long::compareTo)))
                .toList();

        // 为每个节点递归设置子节点
        for (U node : sortedList) {
            List<U> children = buildTreeListByGroupMap(groupMap, node.getId());
            if (CollectionUtils.isNotEmpty(children)) {
                node.setChildrenList(children);
            }
        }

        return sortedList;
    }
}
